<script setup>
import { ref, reactive } from "vue";
import {
  NButton,
  NCheckbox,
  NBreadcrumb,
  NBreadcrumbItem,
  useDialog,
  useMessage,
  NPopover,
  NSpin,
} from "naive-ui";
import store from "@/store";
import { getGoodsSku } from "@/api/cart";
import router from "@/router";

let isAll = ref(true);
isAll.value = store.getters.isCheckAll;
const dialog = useDialog();
const goods = ref({});
const message = useMessage();
let loading = ref(true);
let btnLoading = ref(false);
let cartLoading = ref(false);

const updateSelected = (item) => {
  store.dispatch("updateCart", item).then((res) => {
    isAll.value = res;
  });
};
const delCart = (skuId) => {
  dialog.warning({
    title: "警告",
    content: "确定删除当前商品？",
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: () => {
      cartLoading.value = true;
      store.dispatch("deleteCart", skuId).then(() => {
        message.success("删除成功!");
        cartLoading.value = false;
      });
    },
  });
};
// 全选商品或取消全选
const selCartAll = () => {
  store.dispatch("selectedCartAll").then((res) => {
    isAll.value = res;
  });
};
// 删除选中的商品
const checkDel = (isClear) => {
  if (store.getters.selectedTotal > 0 || isClear) {
    dialog.warning({
      title: "警告",
      content: `确定删除当前${isClear ? "失效的" : "选中的"}的商品？`,
      positiveText: "确定",
      negativeText: "取消",
      onPositiveClick: () => {
        cartLoading.value = true;
        store.dispatch("deleteSelCart", isClear).then(() => {
          cartLoading.value = false;
          message.success("删除成功!");
        });
      },
    });
  } else {
    message.warning("当前没有选择商品");
  }
};
// 修改数量
const updateCount = (skuId, count) => {
  store.dispatch("updateCart", { skuId, count });
};

const skuInfo = (status, skuId) => {
  loading.value = true;
  if (status) {
    getGoodsSku(skuId).then((res) => {
      goods.value = res;
      loading.value = false;
    });
  } else {
    goods.value = {};
    loading.value = true;
  }
};

// 监听Sku 改变
const currSku = ref(null);
const skuChange = (sku) => {
  currSku.value = sku;
};
// 修改商品规格
const commitSku = (skuId) => {
  if (currSku.value && currSku.value.skuId && currSku.value.skuId !== skuId) {
    btnLoading.value = true;
    store
      .dispatch("updateCartSku", { oldSkuId: skuId, newSku: currSku.value })
      .then(() => {
        message.success("修改规格成功");
        btnLoading.value = false;
      });
  } else if (!currSku.value.skuId) {
    message.error("请选择商品规格");
  } else {
    message.warning("当前商品规格无变化");
  }
};

// 结算下单
const checkOut = () => {
  // 判断是否选中了商品
  if (store.getters["selectedList"].length === 0) {
    message.warning("至少勾选一件商品");
    return;
  }
  // 弹出确认框 提示 下单结算需要登录
  router.push("/member/checkout");
  // dialog.warning({
  //   title: "警告",
  //   content: `下单结算需要登录，确认现在去登录吗？`,
  //   positiveText: "确定",
  //   negativeText: "取消",
  //   onPositiveClick: () => {
  //     router.push("/login");
  //   },
  // });
  // 使用导航守卫  需要登录的拦截到登录页面
};
</script>

<template>
  <div class="cart-page bg">
    <div class="container">
      <n-breadcrumb style="padding: 20px 0px">
        <n-breadcrumbItem href="/">首页</n-breadcrumbItem>
        <n-breadcrumbItem href="">购物车</n-breadcrumbItem>
      </n-breadcrumb>
      <n-spin :show="cartLoading">
        <div class="cart">
          <table>
            <thead>
              <tr>
                <th width="120">
                  <n-checkbox
                    @update:checked="selCartAll"
                    v-model:checked="isAll"
                    >全选</n-checkbox
                  >
                </th>
                <th width="400">商品信息</th>
                <th width="220">单价</th>
                <th width="180">数量</th>
                <th width="180">小计</th>
                <th width="140">操作</th>
              </tr>
            </thead>
            <!-- 有效商品 -->
            <tbody>
              <tr v-if="!store.getters.validList.length">
                <td colspan="6">
                  <div class="cartNull">
                    <img
                      src="@/assets/images/d0736561-5222-4653-a10c-a933170e9e80.png"
                      alt=""
                    />
                    <p>购物车暂时没有商品</p>
                    <router-link to="/">
                      <n-button type="primary">去逛逛</n-button>
                    </router-link>
                  </div>
                </td>
              </tr>
              <tr v-for="item in store.getters.validList" :key="item.skuId">
                <td>
                  <n-checkbox
                    v-model:checked="item.selected"
                    @update:checked="updateSelected(item)"
                  ></n-checkbox>
                </td>
                <td>
                  <div class="goods">
                    <RouterLink :to="`/product/${item.id}`"
                      ><img :src="item.picture" alt=""
                    /></RouterLink>
                    <div>
                      <p class="name ellipse">
                        {{ item.name }}
                      </p>
                      <!-- 选择规格组件 -->
                      <n-popover
                        trigger="click"
                        placement="bottom"
                        @update:show="($event) => skuInfo($event, item.skuId)"
                      >
                        <template #trigger>
                          <span class="ellipse attrs"
                            >{{ item.attrsText
                            }}<i class="iconfont icon-down"></i
                          ></span>
                        </template>
                        <n-spin :show="loading">
                          <div v-if="!loading" style="max-width: 500px">
                            <goods-sku
                              :skuId="item.skuId"
                              :goods="goods"
                              @change="skuChange"
                            ></goods-sku>
                            <n-button
                              type="primary"
                              :loading="btnLoading"
                              style="margin-left: 70px; margin-bottom: 10px"
                              @click="commitSku(item.skuId)"
                              size="small"
                              >确认</n-button
                            >
                          </div>
                          <div v-else style="height: 100px; width: 200px"></div>
                        </n-spin>
                      </n-popover>
                    </div>
                  </div>
                </td>
                <td class="tc">
                  <p>&yen;{{ item.nowPrice }}</p>
                  <p v-if="item.price - item.nowPrice > 0">
                    比加入时降价
                    <span class="red"
                      >&yen;{{ item.price - item.nowPrice }}</span
                    >
                  </p>
                </td>
                <td class="tc">
                  <num-box
                    @change="($event) => updateCount(item.skuId, $event)"
                    :modelValue="item.count"
                    :max="item.stock"
                  ></num-box>
                </td>
                <td class="tc">
                  <p class="f16 red">
                    &yen;{{ (item.nowPrice * item.count).toFixed(2) }}
                  </p>
                </td>
                <td class="tc">
                  <p><a href="javascript:;">移入收藏夹</a></p>
                  <p>
                    <a
                      class="green"
                      @click="delCart(item.skuId)"
                      href="javascript:;"
                      >删除</a
                    >
                  </p>
                  <p><a href="javascript:;">找相似</a></p>
                </td>
              </tr>
            </tbody>
            <!-- 无效商品 -->
            <tbody v-if="store.getters.invalidList.length">
              <tr>
                <td colspan="6"><h3 class="tit">失效商品</h3></td>
              </tr>
              <tr v-for="item in store.getters.invalidList" :key="item.skuId">
                <td><n-checkbox style="color: #eee" /></td>
                <td>
                  <div class="goods">
                    <RouterLink to="/"
                      ><img :src="item.picture" alt=""
                    /></RouterLink>
                    <div>
                      <p class="name ellipse">
                        {{ item.name }}
                      </p>
                      <p class="attr">{{ item.attrsText }}</p>
                    </div>
                  </div>
                </td>
                <td class="tc">
                  <p>&yen;{{ item.nowPrice }}</p>
                </td>
                <td class="tc">{{ item.count }}</td>
                <td class="tc">
                  <p>&yen;{{ (item.nowPrice * item.count).toFixed(2) }}</p>
                </td>
                <td class="tc">
                  <p><a class="green" href="javascript:;">删除</a></p>
                  <p><a href="javascript:;">找相似</a></p>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </n-spin>
      <!-- 操作栏 -->
      <div class="action">
        <div class="batch">
          <n-checkbox v-model:checked="isAll" @update:checked="selCartAll"
            >全选</n-checkbox
          >
          <a href="javascript:;" @click="checkDel(false)">删除商品</a>
          <a href="javascript:;">移入收藏夹</a>
          <a href="javascript:;" @click="checkDel(true)">清空失效商品</a>
        </div>
        <div class="total">
          共 <span>{{ store.getters.validTotal }}</span> 件商品，已选择
          <span>{{ store.getters.selectedTotal }}</span> 件，商品合计：
          <span class="red">{{ store.getters.selectedAmount.toFixed(2) }}</span>
          <n-button type="primary" @click="checkOut">下单结算</n-button>
        </div>
      </div>
      <!-- 猜你喜欢 -->
      <goods-relevant />
    </div>
  </div>
</template>

<style scoped lang='less'>
.tc {
  text-align: center;
  .numbox {
    margin: 0 auto;
    width: 120px;
  }
}
.red {
  color: @priceColor;
}
.green {
  color: @xtxColor;
}
.f16 {
  font-size: 16px;
}
.goods {
  .trigger {
    color: #999;
    font-size: 13px;
  }
  .name {
    margin: 5px 0px;
  }
  display: flex;
  align-items: center;
  img {
    width: 100px;
    height: 100px;
  }
  > div {
    width: 280px;
    font-size: 16px;
    padding-left: 10px;
    .attr {
      font-size: 14px;
      color: #999;
    }
  }
}
.action {
  display: flex;
  background: #fff;
  margin-top: 20px;
  height: 80px;
  align-items: center;
  font-size: 16px;
  justify-content: space-between;
  padding: 0 30px;
  .checkbox {
    color: #999;
  }
  .batch {
    a {
      margin-left: 20px;
      font-size: 14px;
    }
  }
  .red {
    font-size: 18px;
    margin-right: 20px;
    font-weight: bold;
  }
  .total {
    font-size: 14px;
    span {
      color: @priceColor;
    }
  }
}
.tit {
  color: #666;
  font-size: 16px;
  font-weight: normal;
  line-height: 50px;
}
.cart-page {
  .cart {
    background: #fff;
    color: #666;
    table {
      border-spacing: 0;
      border-collapse: collapse;
      line-height: 24px;
      th,
      td {
        padding: 10px;
        border-bottom: 1px solid #f5f5f5;
        &:first-child {
          text-align: left;
          padding-left: 30px;
          color: #999;
        }
      }
      th {
        font-size: 16px;
        font-weight: normal;
        line-height: 50px;
      }
    }
  }
}
.cartNull {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-flow: column nowrap;
  padding: 100px;
  img {
    height: 300px;
    width: 300px;
    object-fit: cover;
  }
  p {
    font-size: 15px;
    margin-bottom: 10px;
  }
}
.attrs {
  cursor: pointer;
  font-size: 13px;
  color: #999;
  i {
    margin-left: 5px;
  }
}
</style>